<?php
/**
 * Geocontexter
 * @link http://code.google.com/p/geocontexter/
 * @package Geocontexter
 */

/**
 * Json Record Update controller for general data entry form
 *
 *
 * @package Geocontexter
 * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
 * @author Armand Turpel <geocontexter@gmail.com>
 * @version $Rev$ / $LastChangedDate$ / $LastChangedBy$
 */

namespace Youobserve\Controller;

use Zend\View\Model\JsonModel;
use Youobserve\Controller\AbstractIdentityController;


class JsonRecordUpdateController extends AbstractIdentityController
{

    protected function init($controller)
    {

    }

    public function indexAction()
    {
    	$images = $this->request->getPost()->images;

		$media_folder_hash = '';

		if (isset($images) && (count($images) > 0)) {
			$media_folder_hash = md5(time() . uniqid('',true));
		}

        $error = array();

        $id_record = (int)$this->request->getPost()->id_record;

        $params = array('id_record' => $id_record,
                        'data'      => array('id_item'            => (int)$this->request->getPost()->id_item,
                                             'id_modifier'        => $this->get_identity()->id_user,
                                             'id_context'         => 1000000000000000,
                                             'id_project'         => 1000000000000000,
                                             'id_attribute_group' => 1000000000000006,
                                             'id_status'          => 1000,
                                             'date_record_start'  => $this->request->getPost()->date_record_start,
                                             'date_record_end'    => $this->request->getPost()->date_record_end,
                                             'media_folder_hash'  => $media_folder_hash
                       ));

        if ($params['data']['id_item'] === null) {
            $error[] = 'id_item isnt defined';
        }

        if ($params['data']['date_record_start'] === null) {
            $error[] = 'date_record_start isnt defined';
        }

        if ($params['data']['date_record_end'] === null) {
            $error[] = 'date_record_end isnt defined';
        }

        $geometry = $this->request->getPost()->geom;

        if (false !== strstr($geometry, ',')) {
            $_geom = explode(',', $geometry);
        } elseif (false !== strstr($geometry, ' ')) {
            $_geom = explode(' ', $geometry);
        } else {
            $error[] = 'Longitude/Latitude isnt separated by space or comma.';
        }

        if (!isset($_geom[0]) || !isset($_geom[1])) {
            $error[] = 'Geographic reference is wrong';
        } else {
            $params['geom_point'] = $this->build_geometry(trim($_geom[1]), trim($_geom[0]));
        }

		$AttributeHstoreEncode = $this->CoreModel('AttributeHstoreEncode2');

		$_attributes = array('record_abundance'          => $this->request->getPost()->abundance,
		                     'record_abundance_accuracy' => $this->request->getPost()->accuracy,
		                     'observer'                  => $this->request->getPost()->observer,
		                     'determiner'                => $this->request->getPost()->determiner,
		                     'record_comment'            => $this->request->getPost()->comment,
		                     'record_site_comment'       => $this->request->getPost()->site_comment);

		$serialized_attributes = $AttributeHstoreEncode->encode( $params['data']['id_attribute_group'], $_attributes );

		$params['data']['attribute_value'] = $serialized_attributes['hstore'];

        if (count($error) > 0) {
            return new JsonModel(array('error' => $error));
        }

        $RecordUpdate = $this->CoreModel('RecordUpdate');

        try {

          	$update_result  = $RecordUpdate->run( $params );

          	//die(var_export($update_result,true));

			if (!empty($media_folder_hash)) {

			    $tmp_image_path = $this->sessionOffsetGet('tmp_image_path');

			    $RecordImageAdd    = $this->CoreModel('RecordImageAdd');
			    $RecordImageUpdate = $this->CoreModel('RecordImageUpdate');

				if (!is_dir(GEOCONTEXTER_ROOT . '/public/data/gc_record/' . $id_record . '_' . $media_folder_hash)) {
					mkdir(GEOCONTEXTER_ROOT . '/public/data/gc_record/' . $id_record . '_' . $media_folder_hash);
					mkdir(GEOCONTEXTER_ROOT . '/public/data/gc_record/' . $id_record . '_' . $media_folder_hash . '/image');
					mkdir(GEOCONTEXTER_ROOT . '/public/data/gc_record/' . $id_record . '_' . $media_folder_hash . '/image/thumbnail');
				}

				$tmp_folder = GEOCONTEXTER_ROOT . '/public/data/tmpuploads/' . $tmp_image_path;

				$x = 0;

				foreach ($images['i_name'] as $img) {

				    if (!empty($id_media = trim($images['i_id_media'][$x]))) {

						$params = array('id_media'    => $id_media,
										'data' => array('title'           => $images['i_title'][$x],
											            'description'     => $images['i_description'][$x],
											            'preferred_order' => $x
										));

						$RecordImageUpdate->run($params);

				    } else {

						$info = getimagesize ( $tmp_folder . '/' . $img );

						$params = array('id_record'       => $id_record,
										'title'           => $images['i_title'][$x],
										'preferred_order' => $x,
										'description'     => $images['i_description'][$x],
										'media'           => array('file_name'   => $img,
															   'file_mime'       => $info['mime'],
															   'file_width'      => $info[0],
															   'file_height'     => $info[1],
															   'file_size'       => filesize($tmp_folder . '/' . $img))
										);

						$RecordImageAdd->run($params);

					}

					$x++;
				}

				$RecordImageUpload = $this->CoreModel('RecordImageUpload');


				$params  = array('image_folder_path'        => GEOCONTEXTER_ROOT . '/public/data/gc_record/' . $id_record . '_' . $update_result['media_folder_hash'] . '/image',
								 'source_image_folder_path' => GEOCONTEXTER_ROOT . '/public/data/tmpuploads/' . $tmp_image_path,
								 'delete_source'            => true
								);

				$result  = $RecordImageUpload->run( $params );

			} else {
				// delete possible images

				$this->delete_source(GEOCONTEXTER_ROOT . '/public/data/gc_record/' . $id_record . '_' . $update_result['media_folder_hash'] . '/image');
				$this->delete_source(GEOCONTEXTER_ROOT . '/public/data/tmpuploads/' . $tmp_image_path);

			}

          	return new JsonModel(array('result' => array('id_record' => $id_record)));

        } catch (\Exception $e) {

          	$this->default_error = "Error\n File: " . __file__ . "\nLine: " . __line__ . "\nError: " . $e->__toString();


          	return new JsonModel(array('error' => $this->default_error));

        }
    }
    private function build_geometry($latitude, $longitude)
    {
        return "ST_GeometryFromText('POINT({$longitude} {$latitude})',4326)";
    }

    public function imageAddAction()
    {
		require(GEOCONTEXTER_ROOT . '/public/library/jQuery-File-Upload-master/YouobserveUploadHandler.php');

		if (true === $this->sessionOffsetExists('tmp_image_path')) {

			$tmp_image_path = $this->sessionOffsetGet('tmp_image_path');

		} else {

			$tmp_image_path = md5(time() . rand());
			mkdir(GEOCONTEXTER_ROOT . '/public/data/tmpuploads/' . $tmp_image_path);
			$this->sessionOffsetSet('tmp_image_path', $tmp_image_path);

		}

		$options = array('upload_dir'        => GEOCONTEXTER_ROOT . '/public/data/tmpuploads/' . $tmp_image_path . '/',
		                 'upload_url'        => $this->getBaseUrl().'/data/tmpuploads/' . $tmp_image_path . '/',
		                 'image_folder_name' => $tmp_image_path);

		$upload_handler = new \UploadHandler($options);
		exit;
    }

    public function imageRemoveAction()
    {

    	$id_media = $this->request->getPost()->id_media;

        $RecordMediaDelete = $this->CoreModel('RecordMediaDelete');

		$params  = array('id_media' => $id_media);

        $result = $RecordMediaDelete->run( $params );

        die(json_encode(array('success' => true,
                              'media'   => $result)));
    }

    /**
     * upload lists backup file for import
     */
    public function move_images($source, $dest)
    {
		foreach (
		 $iterator = new \RecursiveIteratorIterator(
		  new \RecursiveDirectoryIterator($source, \RecursiveDirectoryIterator::SKIP_DOTS),
		  \RecursiveIteratorIterator::SELF_FIRST) as $item
		) {
		  if ($item->isDir() && !is_dir($dest . DIRECTORY_SEPARATOR . $iterator->getSubPathName())) {
			mkdir($dest . DIRECTORY_SEPARATOR . $iterator->getSubPathName());
		  } else {
			copy($item, $dest . DIRECTORY_SEPARATOR . $iterator->getSubPathName());
		  }
		}
    }

	public static function delete_source($dir) {
		$iterator = new \RecursiveDirectoryIterator($dir, \RecursiveDirectoryIterator::SKIP_DOTS);
		foreach (new \RecursiveIteratorIterator($iterator, \RecursiveIteratorIterator::CHILD_FIRST) as $file) {
			  if (!$file->isDir()) {
				 unlink($file->getPathname());
			  }
		}
	}

}
